﻿<%@ WebHandler Language="C#" Class="APSPlanDashBoard" %>

using System;
using System.Web;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Converters;
using System.Collections.Generic;
using System.Data;
using System.Text;
using ReportBusiness;
using System.Collections;
using System.IO;

/**
 * Description: APS排产看板
 * Copyright (c): 通力凯顿（北京）系统集成有限公司
 * Author: zhunan
 * Date: 2022.11.7
 */

public class APSPlanDashBoard : IHttpHandler
{
    uMESReportOracleDAL dal = new uMESReportOracleDAL();
    public bool IsReusable { get { return false; } }
    public void ProcessRequest(HttpContext context)
    {
        string requestjson = "";
        using (StreamReader reader = new StreamReader(context.Request.InputStream)) { requestjson = reader.ReadToEnd(); }
        JObject jObject = JsonConvert.DeserializeObject(requestjson) as JObject;
        if (jObject["type"] != null)
        {
            try
            {
                Result r = new Result();
                context.Response.ContentType = "text/json";
                string type = jObject["type"].ToString();
                switch (type)
                {
                    case "getData":
                        r = getData(jObject);//查询
                        context.Response.Write(JsonConvert.SerializeObject(r));
                        break;
                    default:
                        break;
                }
            }
            catch (Exception e)
            {
                Result r = new Result();
                r.data = null;
                r.meta = new Result.Meta(500, e.Message);
                r.total = 0;
                context.Response.ContentType = "text/json";
                context.Response.Write(JsonConvert.SerializeObject(r));
            }
        }
    }

    Result getData(JObject jObject)
    {
        string factoryid = "", workcenterid = "", teamid = "";
        JArray selectOrg = JArray.Parse(jObject["selectOrg"].ToString());
        if (selectOrg.Count == 3)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
            teamid = selectOrg[2].ToString();
        }
        else if (selectOrg.Count == 2)
        {
            factoryid = selectOrg[0].ToString();
            workcenterid = selectOrg[1].ToString();
        }
        else if (selectOrg.Count == 1)
        {
            factoryid = selectOrg[0].ToString();
        }
        string sql = @"
SELECT rd.resourceid,rd.resourcename,rd.description
FROM apsplandetail a
LEFT JOIN ApsPlanDetailEmp ad ON ad.apsplandetailid = a.apsplandetailid AND ad.Isuse = 0
INNER JOIN containercurrentinfo cci ON cci.containerid = a.containerid
LEFT JOIN employee e ON e.employeeid = ad.employeeid
LEFT JOIN Resourcedef rd ON rd.resourceid = a.resourceid
WHERE a.isuse = 0 AND rd.resourceid IS NOT NULL {0}
GROUP BY rd.resourceid,rd.resourcename,rd.description";
        string query = "";
        //工序所属分厂
        if (factoryid != "")
        {
            query += string.Format(" AND a.specfactoryid = '{0}'", factoryid);
        }

        if (workcenterid != "")
        {
            query += string.Format(" AND a.workcenterid = '{0}'", workcenterid);
        }

        if (teamid != "")
        {
            query += string.Format(" AND a.teamid = '{0}'", teamid);
        }

        if (jObject["workerid"] != null && jObject["workerid"].ToString() != "")
        {
            query += string.Format(" AND ad.employeeid = '{0}'", jObject["workerid"].ToString());
        }

        if (jObject["resourcename"] != null && jObject["resourcename"].ToString() != "")
        {
            query += string.Format(" AND rd.resourcename = '{0}'", jObject["resourcename"].ToString());
        }

        if (jObject["mfgordername"] != null && jObject["mfgordername"].ToString() != "")
        {
            query += string.Format(" AND cci.mfgordername = '{0}'", jObject["mfgordername"].ToString());
        }

        if (jObject["productname"] != null && jObject["productname"].ToString() != "")
        {
            query += string.Format(" AND cci.productname = '{0}'", jObject["productname"].ToString());
        }

        if (jObject["containername"] != null && jObject["containername"].ToString() != "")
        {
            query += string.Format(" AND cci.containername = '{0}'", jObject["containername"].ToString());
        }

        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                query += string.Format(" AND a.endtime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                query += string.Format(" AND a.endtime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }

        sql = string.Format(sql, query);
        uMESPagingDataDTO dto = dal.GetPagingDataIns(sql, (int)jObject["currentPage"], (int)jObject["pageSize"]);
        DataTable dtResult = dto.DBTable;

        JArray colums = JArray.Parse(jObject["colums"].ToString());
        for (int i = 0; i < colums.Count; i++)
        {
            dtResult.Columns.Add(colums[i].ToString(), typeof(object));
        }

        sql = @"
SELECT a.apsplandetailid,cci.containerid,cci.workflowstepid,a.resourceid,f.factoryname,w.workcentername,t.teamname,e.fullname,
       rd.resourcename,rd.description,cci.mfgordername,mfg.qty mfgqty,mfg.plannedstartdate,
       cci.productname,cci.productdescription,cci.containerno,
       cci.containername,cci.qty,s.specno,s.opdesc,ws.workflowstepname,
       a.starttime,TRUNC(a.endtime) endtime,csd.checkdate,
       CASE WHEN csd.usecompleted = 1 AND csd.checkdate <= a.endtime THEN '按时完成'
           WHEN csd.usecompleted = 1 AND csd.checkdate > a.endtime THEN '超期完成'
           WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE <= a.endtime THEN '未完成'
           WHEN NVL(csd.usecompleted,0) = 0 AND SYSDATE > a.endtime THEN '超期未完'
       END status
FROM apsplandetail a
LEFT JOIN ApsPlanDetailEmp ad ON ad.apsplandetailid = a.apsplandetailid AND a.isuse = 0
INNER JOIN containercurrentinfo cci ON cci.containerid = a.containerid
LEFT JOIN factory f ON f.factoryid = a.specfactoryid --排产分厂
LEFT JOIN Workcenter w ON w.workcenterid = a.workcenterid --排产工区
LEFT JOIN team t ON t.teamid = a.teamid --排产班组
LEFT JOIN employee e ON e.employeeid = ad.employeeid
LEFT JOIN Resourcedef rd ON rd.resourceid = a.resourceid
LEFT JOIN Workflowstep ws ON ws.workflowstepid = a.workflowstepid
LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
LEFT JOIN mfgorder mfg ON mfg.mfgorderid = cci.mfgorderid
LEFT JOIN (
    SELECT csd.*,row_number () OVER (PARTITION BY csd.containerid, csd.workflowstepid ORDER BY csd.checkdate) as rn
    FROM apsplandetail a
    INNER JOIN containersteprecord csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid
    WHERE a.isuse = 0";
        if (jObject["selectdate"] != null && jObject["selectdate"].ToString() != "")
        {
            JArray arr = JArray.Parse(jObject["selectdate"].ToString());
            if (arr.Count >= 2)
            {
                sql += string.Format(" AND a.endtime >= to_date('{0} 00:00:00','yyyy-MM-dd hh24:mi:ss')", arr[0].ToString());
                sql += string.Format(" AND a.endtime <= to_date('{0} 23:59:59','yyyy-MM-dd hh24:mi:ss')", arr[1].ToString());
            }
        }
        sql += @"
) csd ON csd.containerid = a.containerid AND csd.workflowstepid = a.workflowstepid AND csd.rn = 1
WHERE a.isuse = 0 AND rd.resourceid IS NOT NULL {0}
ORDER BY a.starttime,cci.containername";
        sql = string.Format(sql, query);
        DataTable dt = dal.GetDataTable(sql);
        foreach (DataRow dr in dtResult.Rows)
        {
            for (int i = 5; i < dtResult.Columns.Count; i++)
            {
                string filter = string.Format("resourceid = '{0}' AND endtime='{1}'", dr["resourceid"], dtResult.Columns[i].ColumnName);
                DataRow[] drList = dt.Select(filter);
                DataTable dtPlanSpec;
                if (drList.Length > 0)
                {
                    dtPlanSpec = drList.CopyToDataTable();
                    foreach (DataColumn col in dtPlanSpec.Columns)
                    {
                        col.ColumnName = col.ColumnName.ToLower();
                    }
                    dr[dtResult.Columns[i].ColumnName] = dtPlanSpec;
                }
                else
                {
                    dr[dtResult.Columns[i].ColumnName] = new DataTable();
                }
            }
        }

        foreach (DataColumn col in dtResult.Columns)
        {
            col.ColumnName = col.ColumnName.ToLower();
        }
        Result r = new Result();
        r.data = dtResult;
        r.total = Convert.ToInt32(dto.RowCount);
        r.meta = new Result.Meta(200, "请求成功");
        return r;
    }
}